﻿//=====================================================
// Copyright © 2017-2018 xuxuzhaozhao
// All rights reserved
// GUID: 2a77f0ac-aa57-4dbe-8e60-a202e6954efc
// CLR版本: 4.0.30319.42000
// 新建项输入的名称: ArticleFormatter
// 机器名称: WIN10-20170502F
// 注册组织名: 成都名门汇科技有限公司（谊诚科技）
// 命名空间名称: UnitTestingWebAPI.API.Core.MediaTypeFormatters
// 文件名: ArticleFormatter
// 当前系统时间: 2017/10/21 17:40:07
// 当前登录用户名: xuxuzhaozhao
//======================================================

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using UnitTestingWebAPI.Domain;

namespace UnitTestingWebAPI.API.Core.MediaTypeFormatters
{
    public class ArticleFormatter : BufferedMediaTypeFormatter
    {
        public ArticleFormatter()
        {
            //SupportedMediaTypes.Clear();
            //SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override bool CanWriteType(Type type)
        {
            //for single article object
            if (type == typeof(Article))
                return true;
            else
            {
                // for multiple article objects
                Type _type = typeof(IEnumerable<Article>);
                return _type.IsAssignableFrom(type);
            }
        }

        public override void WriteToStream(Type type,
                                           object value,
                                           Stream writeStream,
                                           HttpContent content)
        {
            using (StreamWriter writer = new StreamWriter(writeStream))
            {
                var articles = value as IEnumerable<Article>;
                if (articles != null)
                {
                    foreach (var article in articles)
                    {
                        writer.Write(
                            $"[{article.ID},\"{article.Title}\",\"{article.Author}\",\"{article.URL}\",\"{article.Contents}\"]");
                    }
                }
                else
                {
                    var article = value as Article;
                    if (article == null)
                    {
                        throw new InvalidOperationException("Cannot serialize type");
                    }
                    writer.Write(
                        $"[{article.ID},\"{article.Title}\",\"{article.Author}\",\"{article.URL}\",\"{article.Contents}\"]");
                }
            }
        }
    }
}
